import Vue from 'vue'
import Vuex from 'vuex'
import { changeUsername, getUserInfo } from '../api/user'
import { getLocal, setLocal, delLocal } from '../utils'

Vue.use(Vuex)

const store = new Vuex.Store({
    state() {
        const info = getLocal('info') 
        return {
            info: info || {},
            isLogin: !!info,
            activeIndex: getLocal('activeIndex') || "1",
        }
    },
    mutations: {
        /**
         * 登录成功, 更改用户信息和登录状态
         * @param {*} state 
         * @param {*} info 
         */
        setInfo(state, info) {
            state.info = {...state.info, ...info}
            setLocal('info', state.info)
            state.isLogin = true
        },
        /**
         * 更改头像
         * @param {*} state 
         * @param {*} avatar 
         */
        changeAvatar(state, avatar) {
            state.info.avatar = avatar
            setLocal('info', state.info)
        },
        /**
         * 退出登录
         */
        logout(state, cb) {
            state.isLogin = false
            state.info = {}
            delLocal('info')
            state.activeIndex = '1'
            cb && cb()
        },

        /**
         * 设置激活的index
         * @param {*} state 
         * @param {*} key 
         */
        setActiveIndex(state, key) {
            state.activeIndex = key
            setLocal('activeIndex', key)
        }
    },
    actions: {
        // 获取用户信息
        async getUserInfo({commit}) {
            const info = await getUserInfo()
            commit('setInfo', info.data)
        },
        /**
         * 更改用户信息
         */
        async changeUserInfo({commit}, username) {
            const res = await changeUsername(username)
            if (res.code === 1) {
                try {
                    commit('setInfo', {username})
                } catch(e) {
                }
            }
            return res
        }
    }
})

export default store